package persistence;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ManyToOneProperty extends PersistentProperty {

	private static Logger log = LoggerFactory.getLogger(ManyToOneProperty.class);

	private Class<?> clazz;

	/**
	 * Constructeur
	 * 
	 * @param persistentClass
	 * @param method
	 */
	public ManyToOneProperty(PersistentClass persistentClass, Method method) {
		super(persistentClass, method);
		this.clazz = method.getReturnType();
		log.debug("ManyToOneProperty sur la méthode [" + method.getName() + "] de la classe [" + this.clazz + "]");
	}

	/**
	 * 
	 */
	public Object getValue(Object bean) throws PersistenceException {

		// Retrouver la Peristence class à partir du bean
		Object result = super.getValue(bean);
		PersistentClass pc = PersistenceUtil.getConfiguration().getPersistentClass(result.getClass());

		// Retourner id
		return pc.getId().getValue(result);
	}

	/**
	 * 
	 */
	public void setValue(Object bean, Object value) throws PersistenceException {
		log.debug("ManyToOneProperty::SetValue");

		// Instancier une catégorie
		PersistentClass pc = PersistenceUtil.getConfiguration().getPersistentClass(this.clazz);
		Object result = null;

		try {
			result = pc.createInstance();
		} catch (Exception e) {
			log.error("Impossible de créer une instance", e);
		}

		// Valoriser son id
		pc.getId().setValue(result, value);

		// Valoriser le bean avec le résultat
		super.setValue(bean, result);

	}

	/**
	 * @param bean
	 * @param session
	 * @throws Exception
	 */
	public Object updateBean(Object bean, PersistenceSession session) throws Exception {
		Object result = this.getValue(bean);
		result = session.get(this.clazz, result);
		super.setValue(bean, result);
		return result;
	}
}
